package view.components;

import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;

import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JTextField;

import model.Constants;
import controller.IpDocument;

public class IPTextArea extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private final ArrayList<JTextField> textList = new ArrayList<JTextField>();
	private final ArrayList<JTextField> dotList = new ArrayList<JTextField>();

	public IPTextArea() {

		this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));

		for (int i = 0; i < 7; i++) {
			if (i % 2 == 0 || i == 0) {
				this.add(textField());
			} else {
				this.add(dotField());
			}
		}

	}

	private JTextField textField() {
		final JTextField text = new JTextField(3);

		textList.add(text);
		text.setBorder(null);
		text.setDocument(new IpDocument());
		text.addKeyListener(new KeyAdapter() {


			@Override
			public void keyReleased(KeyEvent e) {
				switch (e.getKeyCode()) {
				case 37:

					int newindex = textList.indexOf(text) - 1;
					setFokus(newindex);
					break;
				case 39:
					newindex = textList.indexOf(text) + 1;
					setFokus(newindex);
					break;
				case 8:
					if (text.getText().length() == 0) {
						newindex = textList.indexOf(text) - 1;
						setFokus(newindex);
					}
					break;
				case 127:
					if (text.getText().length() == 0) {
						newindex = textList.indexOf(text) - 1;
						setFokus(newindex);
					}
					break;
				default:
					if (text.getText().length() > 2) {
						setFokus(textList.indexOf(text) + 1);
					}

					break;
				}

			}

		});
		return text;
	}

	private void setFokus(int newindex) {
		if (newindex >= 0 && newindex < textList.size())
			textList.get(newindex).requestFocus();
		else {
			this.requestFocus();
		}
	}

	private JTextField dotField() {
		JTextField text = new JTextField(1);
		dotList.add(text);
		text.setText(Constants.POINT);
		text.setBorder(null);
		text.setEditable(false);
		text.setBackground(new Color(255, 255, 255));
		text.setFocusable(false);
		return text;
	}

	public ArrayList<JTextField> getTextList() {
		return textList;
	}

	public ArrayList<JTextField> getDotList() {
		return dotList;
	}



}
